package com.shop.core.util;

import java.security.MessageDigest;

/**
 * MD5工具类
 * 
 * @author Shine
 * @date 2016年6月20日14:54:23
 * @version 1.0
 *
 */
public class MD5Util {
	private final static String[] HEXDIGITS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
			"e", "f" };

	/**
	 * 转换字节数组为16进制字串
	 * 
	 * @param b字节数组
	 * @return 16进制字串
	 */
	private static String byteToHexString(byte byteData) {
		int n = byteData;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return HEXDIGITS[d1] + HEXDIGITS[d2];
	}

	private static String byteArrayToHexString(byte[] byteData) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			resultSb.append(byteToHexString(byteData[i]));
		}
		return resultSb.toString();
	}

	/**
	 * 字符串转MD5
	 * 
	 * @param data
	 * @return
	 */
	public static String MD5Encode(String data) {
		String resultString = null;
		try {
			resultString = new String(data);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return resultString;
	}
}
